package com.itheima.project.listen;

import com.alibaba.fastjson.JSON;
import com.itheima.project.binding.CartSink;
import com.itheima.project.constant.AppletCacheConstant;
import com.itheima.project.pojo.MqMessage;
import com.itheima.project.service.IDishService;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.vo.OrderItemVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;
/**
 * @Description:
 * @Version: V1.0
 */
@Component
@Slf4j
public class CartSinkListener {
    @Autowired
    IDishService dishService;
    @Autowired
    RedissonClient redissonClient;
    @StreamListener(CartSink.CART_INPUT)
    public void onMessage(@Payload MqMessage message) {
        // TODO 思考: 如果延迟消息触发，用户已经下单了怎么办?
        log.info("receive message: {}", message);
        //1、回滚数据库菜品库存
        Map<String, Long> map = JSON.parseObject(message.getConten(), Map.class);
        Long dishId = map.get("dishId");
        Long orderNo = map.get("orderNo");
        Boolean flag = dishService.updateDishNumber(1L, dishId);
        if (!flag){
            log.error("CartSinkListener DishStorage delete error......");
            throw new RuntimeException("ShopCartExpireListener DishStorage delete error......");
        }
        //2、回滚redis中的库存
        String keyDish = AppletCacheConstant.REPERTORY_DISH + dishId;
        RAtomicLong atomicLong = redissonClient.getAtomicLong(keyDish);
        long get = atomicLong.addAndGet(1);
        if (EmptyUtil.isNullOrEmpty(get)){
            log.error("CartSinkListener DishStorage refresh error......");
            throw new RuntimeException("ShopCartExpireListener DishStorage refresh error......");
        }
        //3、删除购物车中对应的菜品
        String key = AppletCacheConstant.ORDERITEMVO_STATISTICS + orderNo;
        RMapCache<Long, OrderItemVo> orderItemVoRMap = redissonClient.getMapCache(key);
        orderItemVoRMap.remove(dishId);
        //   TODO 上面Redis和mysql库存补1   这里直接删除购物车菜品  有BUG
        log.info("CartSinkListener DishStorage return success.....");
    }
}